﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace System
{
	public static class StringExtensions
	{
		public static string[] SplitLines(this string str)
		{
			return str == null ? null
				: str.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
		}

		public static string JoinLines(this IEnumerable<string> enumerable)
		{
			return enumerable == null ? null : String.Join(Environment.NewLine, enumerable);
		}

		public static string Args(this string format, params object[] parameters)
		{
			return String.Format(CultureInfo.CurrentCulture, format, parameters);
		}

		public static string Args(this string format, IFormatProvider provider, params object[] parameters)
		{
			return String.Format(provider, format, parameters);
		}

		public static string Join(this IEnumerable<string> enumerable, string separator)
		{
			return enumerable == null ? null : String.Join(separator, enumerable);
		}

		public static string Format<T>(this T source, string template)
			where T : class
		{
			if (template == null) return null;
			if (source == null) return null;

			var sb = new StringBuilder(template);

			source.GetType().GetProperties()
				.Where(p => p.CanRead)
				.ForEach(prop => prop
					.With(p => '{' + p.Name + '}')
					.With(pattern => pattern
						.If(template.Contains)
						.With(Convert.ToString(prop.GetValue(source, null), CultureInfo.CurrentCulture))
						.With(val => sb.Replace(pattern, val))));

			return sb.ToString();
		}
	}
}
